package com.hontech.dapapp

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Build
import com.hontech.dapapp.utils.log
import kotlinx.coroutines.CompletableDeferred


const val ACTION_USB_PERMISSION = "usb.permission"



suspend fun requestUsbPermission(context: Context, device: UsbDevice, usbManager: UsbManager) {
    val receiver = UsbPermissionReceiver()
    val intent = Intent(ACTION_USB_PERMISSION)
    val pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {

        context.registerReceiver(receiver, IntentFilter(ACTION_USB_PERMISSION), Context.RECEIVER_EXPORTED)
    } else {
        context.registerReceiver(receiver, IntentFilter(ACTION_USB_PERMISSION))
    }

    usbManager.requestPermission(device, pi)
    receiver.await()
    context.unregisterReceiver(receiver)
    if (! usbManager.hasPermission(device) ) {
        throw IllegalStateException("需要授权使用CMSIS DAP Link")
    }
}

class UsbPermissionReceiver : BroadcastReceiver() {

    private val promise = CompletableDeferred<Boolean>()

    suspend fun await() = promise.await()

    override fun onReceive(context: Context?, intent: Intent?) {
        log("USB 收到广播")
        if (intent == null) {
            return
        }
        val r = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
        log("权限:$r")
        promise.complete(r)
    }
}

